/**
 * @description 树结构数据叶子节点数据迁移（清空叶子节点并将叶子节点数据复制到父节点childs字段）
 * @param {Array} tree 函数
 */
interface TreeNode {
	id: string;
	childrens?: TreeNode[];
	childs?: TreeNode[];
	isCamera?: number;
	[key: string]: any;
}

interface Config {
	idField?: string;
	childrenField?: string;
	leafField?: string;
}

const changeLeafNode = function (tree: TreeNode[], config: Config = {}): TreeNode[] {
	const currentConfig = {
		...{
			idField: 'id',
			childrenField: 'childrens',
			leafField: 'isCamera',
		},
		...config,
	};
	const result = JSON.parse(JSON.stringify(tree)); // 复制原对象以防修改原数据
	const processNode = (node: TreeNode) => {
		if (
			node[currentConfig.childrenField!] &&
			node[currentConfig.childrenField!].some((child: TreeNode) => child[currentConfig.leafField!] === 1)
		) {
			// 如果当前节点的子节点中存在isCamera === 1
			if (!node.childs) {
				node.childs = [];
			}
			node.childs.push(...node[currentConfig.childrenField!]);
			node[currentConfig.childrenField!] = [];
			// delete node.childrens
		}

		if (node[currentConfig.childrenField!] && node[currentConfig.childrenField!].length > 0) {
			node[currentConfig.childrenField!].forEach((child: TreeNode) => processNode(child));
		}
	};

	processNode(result);
	return result;
};
export default changeLeafNode;
